import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Layout from './components/Layout';
import Home from './components/Home';
import MyPlanet from './components/planet/MyPlanet';
import CarbonCalculator from './components/calculator/CarbonCalculator';
import PersonalChallenges from './components/challenges/PersonalChallenges';
import EnvironmentalTasks from './components/tasks/EnvironmentalTasks';
import Login from './components/auth/Login';
import Register from './components/auth/Register';
import UserProfile from './components/auth/UserProfile';
import { useUserStore } from './store/userStore';
import PlanetEcoPanel from './components/planetecopanel/PlanetEcoPanel';
import { Achievements } from './components/achievements/Achievements';

// 受保护的路由组件
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { isAuthenticated } = useUserStore();
  
  if (!isAuthenticated) {
    return <Navigate to="/login" />;
  }
  
  return <>{children}</>;
};

function App() {
  const { isAuthenticated } = useUserStore();

  return (
    <Router>
      <Routes>
        {/* 公开路由 */}
        <Route path="/" element={isAuthenticated ? <Navigate to="/dashboard/planet" /> : <Home />} />
        <Route path="/login" element={isAuthenticated ? <Navigate to="/dashboard/planet" /> : <Login />} />
        <Route path="/register" element={isAuthenticated ? <Navigate to="/dashboard/planet" /> : <Register />} />
        
        {/* 需要登录的路由 */}
        <Route path="/dashboard/*" element={
          <ProtectedRoute>
            <Layout>
              <Routes>
                <Route path="/" element={<Navigate to="/dashboard/planet" replace />} />
                <Route path="planet" element={<MyPlanet />} />
                <Route path="overview" element={<PlanetEcoPanel />} />
                <Route path="calculator" element={<CarbonCalculator />} />
                <Route path="challenges" element={<PersonalChallenges />} />
                <Route path="tasks" element={<EnvironmentalTasks />} />
                <Route path="achievements" element={<Achievements />} />
              </Routes>
            </Layout>
          </ProtectedRoute>
        } />
        
        {/* 个人资料路由 */}
        <Route path="/profile" element={
          <ProtectedRoute>
            <Layout>
              <UserProfile />
            </Layout>
          </ProtectedRoute>
        } />
      </Routes>
    </Router>
  );
}

export default App;